#!/bin/bash

# shellcheck source=meta-facebook/recipes-fb/obmc_functions/files/fb-common-functions
source /usr/libexec/fb-common-functions

BE_NIC_I2C_LIST="\
32-001f \
35-001f \
44-001f \
47-001f \
"

is_host_on()
{
  local host_power_state=""
  host_power_state="$(busctl get-property xyz.openbmc_project.State.Host /xyz/openbmc_project/state/host0 xyz.openbmc_project.State.Host CurrentHostState | cut -d'"' -f2)"

  if [ "$host_power_state" != "xyz.openbmc_project.State.Host.HostState.Running" ]; then
      return 1
  fi
  return 0
}


ATTEMPT_COUNT=0

while true; do
    if ! is_host_on; then
        sleep 5
        continue
    fi

    ATTEMPT_COUNT=$((ATTEMPT_COUNT + 1))
    ALL_DONE=true
    echo "Attempt $ATTEMPT_COUNT..."

    for dev in $BE_NIC_I2C_LIST; do
        DEVICE_PATH="/sys/bus/i2c/drivers/tmp421/$dev"
        if [ ! -L "$DEVICE_PATH" ]; then
            if ! echo "$dev" > /sys/bus/i2c/drivers/tmp421/bind 2>/dev/null; then
                ALL_DONE=false
            fi
        else
            echo "$dev: already bind, skip"
        fi
    done

    if [ $ALL_DONE = true ]; then
        echo "All devices successfully bind"
        exit 0
    fi

    sleep 5
done